<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.io.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%
//错误信息
String errorMsg = "";

//文件最大值
long maxSize = 1000000;

//定义文件上传的类型
String[] types = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};


String prefix = "/attachment/avatar/origin/";
//文件保存目录路径, TODO 应从配置中取得
String savePath = request.getSession().getServletContext().getRealPath("/")+prefix;

String picId = UUID.randomUUID().toString();

//上传后图片的绝对地址
String picRealPath = request.getContextPath() + prefix + picId+".jpg";

// picRealPath
//文件保存目录URL

//判断是否为单个文件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if(isMultipart){
  
  FileItemFactory factory = new DiskFileItemFactory();
  
  ServletFileUpload upload = new ServletFileUpload(factory);
  
  List items = upload.parseRequest(request);
  
  // Process the uploaded items
  Iterator iter = items.iterator();
  while (iter.hasNext()) {
      FileItem item = (FileItem) iter.next();
      //原文件名
      String fileName = item.getName();
      
      //文件大小
      long  fileSize  = item.getSize();
            
      if (!item.isFormField()) {
        //检查文件名
        if(item.getName()==""||item.getString()==null){
          errorMsg = "请选择文件。";
          break;
        }

        //检查目录
        File uploadDir = new File(savePath);
        if(!uploadDir.isDirectory()){
          errorMsg = "上传目录不存在。";
          break;
        }
        //检查目录写权限
        if(!uploadDir.canWrite()){
          errorMsg = "上传目录没有写权限。";
          break;
        }
        //检查文件大小
        if(item.getSize()>maxSize){
          errorMsg = "上传文件大小超过限制。";
        }
        
        //获得文件扩展名
        // String fileExt = fileName.substring(fileName.indexOf(".")+1);
        String fileExt = "jpg";
        if(!Arrays.<String>asList(types).contains(fileExt.toLowerCase())){
          errorMsg = "上传文件扩展名是不允许的扩展名。";
        } 
        
        //服务器上临时文件名
        // String tempName = new Date().getTime()+"."+fileExt;
        String tempName = picId+"."+fileExt;
        
        //检查是否已上传
        File file = new File(savePath+"\\"+tempName);
        if(file.exists()){
          errorMsg = "临时文件可能不是上传文件。";
        }
        
        //上传文件  
        try{
          File uploadedFile = new File(savePath,tempName);
            
          item.write(uploadedFile);
        }catch(Exception e){
          errorMsg = "上传文件失败。";
        }
        
      }
  }
  
  if(errorMsg.equals("")){
	  out.println("<script type=\"text/javascript\">"+
		        "window.parent.hideLoading();window.parent.buildAvatarEditor(\""+picId+"\",\""+picRealPath+"\",\"photo\");</script>';");
   
  }else{
	  //插入图片，关闭层
    out.println("<script type='text/javascript'>alert('对不起, 上传失败, "+errorMsg+"');</script>");
  }
  
}
%>

